package cn.com.xy.sms.sdk.tagsearch;


import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.XyCursor;
import cn.com.xy.sms.sdk.db.bizport.BizportDBManager;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.log.LogManager;

/**
 * @author kwb1
 * @version 1.0
 * @created 17-02-2017 16:37:50
 * jira : HUAWEI-2296
 */
public class TagDbManager {
    private final String TAG = "TagDbManager";
    private static TagDbManager sTagDbManager = null;
    private final String MAX_TAG_VERSION = "max_tag_version";

    /**
     * 创建表 Start
     **/
    public static final String KEY_ID = "_id";
    //标签-情景id表
    public static final String TABLE_NAME = "tb_scene_tag";

    private static final String KEY_TAG_ID = "tag_id";    //标签id
    private static final String KEY_TAG_NAME = "tag_name";   //标签名称
    private static final String KEY_TAG_PARENT_IDS = "tag_parent_id";  //父标签id
    private static final String KEY_SCENE_IDS = "scene_ids";   //情景id

    private static final String KEY_OFTEN_STATUS = "often_status";    //是否为常用标签
    private static final String KEY_USE_COUNT = "use_count";     // 标签点击次数

    private static final String KEY_VERSION = "version";  //标签最后更改时间
    private static final String KEY_PRIORITY = "priority";  //同一个情景下的标签排序
    private static final String KEY_LAST_USE_TIME = "last_time";       //最新使用的时间

    public static final String DROP_TABLE_TAG = " DROP TABLE IF EXISTS "
            + TABLE_NAME;

    public static final String CREATE_TABLE_TAG = "create table if not exists "
            + TABLE_NAME +
            " ("
            + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_TAG_ID + " Integer,"
            + KEY_TAG_NAME + " VARCHAR Default '',"
            + KEY_TAG_PARENT_IDS + " VARCHAR Default '',"
            + KEY_SCENE_IDS + " TEXT,"
            + KEY_OFTEN_STATUS + " INTEGER ,"
            + KEY_VERSION + " VARCHAR,"
            + KEY_PRIORITY + " INTEGER,"
            + KEY_LAST_USE_TIME + " VARCHAR,"
            + KEY_USE_COUNT + " INTEGER Default 0"
            + ")";

    /**
     * 创建表 end
     **/


    private TagDbManager() {
    }

    public static synchronized TagDbManager getInstance() {
        if (sTagDbManager == null) {
            sTagDbManager = new TagDbManager();
        }
        return sTagDbManager;
    }

    public void clearAll() {
        try {
            BizportDBManager.delete(TABLE_NAME, null, null);
        } catch (Throwable t) {
            LogManager.e(TAG, "clearAll", t);
        }
    }


    public int deleteTag(int tagId) {
        try {
            return BizportDBManager.delete(TABLE_NAME, KEY_TAG_ID + " =?", new String[]{String.valueOf(tagId)});
        } catch (Throwable t) {
            LogManager.e(TAG, "deleteTag", t);
        }
        return -1;
    }

    public Map<String, TagCacheManager.TagItem> getFirstTag() {
        XyCursor cursor = null;
        Map<String, TagCacheManager.TagItem> tagSceneMap = new HashMap<String, TagCacheManager.TagItem>();
        try {
            cursor = BizportDBManager.query(TABLE_NAME, new String[]{KEY_TAG_ID,KEY_TAG_NAME, KEY_SCENE_IDS}, KEY_TAG_PARENT_IDS + "=''", null, null, null, KEY_LAST_USE_TIME + " desc", null);
            if (cursor != null) {
                int tagName = cursor.getColumnIndex(KEY_TAG_NAME);
                int tagIdIndex = cursor.getColumnIndex(KEY_TAG_ID);
                int sceneId = cursor.getColumnIndex(KEY_SCENE_IDS);
                while (cursor.moveToNext()) {
                    String tagId = cursor.getString(tagIdIndex);
                    String tag = cursor.getString(tagName);
                    String sceneIds = cursor.getString(sceneId);
                    tagSceneMap.put(tag, new TagCacheManager.TagItem(tagId,sceneIds));
                }
            }
        } catch (Throwable t) {
            LogManager.e(TAG, "getFirstTag", t);
        } finally {
            XyCursor.closeCursor(cursor, true);
        }


        return tagSceneMap;
    }

    public Map<String, TagCacheManager.TagItem> getSecondTag(String tag1) {
        XyCursor cursor = null;
        Map<String, TagCacheManager.TagItem> tagSceneMap = new HashMap<String, TagCacheManager.TagItem>();
        try {
            cursor = BizportDBManager.query(TABLE_NAME, new String[]{KEY_TAG_ID,KEY_TAG_NAME, KEY_SCENE_IDS}, KEY_TAG_PARENT_IDS + " like '%;" + tag1 + ";%'", null, null, null, KEY_LAST_USE_TIME + " desc", null);
            if (cursor != null) {
                int tagName = cursor.getColumnIndex(KEY_TAG_NAME);
                int tagIdIndex = cursor.getColumnIndex(KEY_TAG_ID);
                int sceneId = cursor.getColumnIndex(KEY_SCENE_IDS);
                while (cursor.moveToNext()) {
                    String tag2 = cursor.getString(tagName);
                    String tagId = cursor.getString(tagIdIndex);
                    String sceneIds = cursor.getString(sceneId);
                    tagSceneMap.put(tag2, new TagCacheManager.TagItem(tagId,sceneIds));
                }
            }
        } catch (Throwable t) {
            LogManager.e(TAG, "getSecondTag", t);
        } finally {
            XyCursor.closeCursor(cursor, true);
        }
        return tagSceneMap;
    }

    public String getTagIdByTagName(String tagName) {
        XyCursor cursor = null;
        String tagId = null;
        try {
            cursor = BizportDBManager.query(TABLE_NAME, new String[]{KEY_TAG_ID}, KEY_TAG_NAME + " =?", new String[]{tagName});
            if (cursor == null) {
                return null;
            }
            if (cursor.moveToFirst()) {
                tagId = cursor.getString(cursor.getColumnIndex(KEY_TAG_ID));
            }
        } catch (Throwable t) {
            LogManager.e(TAG, "getTagIdByTagName", t);
        } finally {
            XyCursor.closeCursor(cursor, true);
        }
        return tagId;
    }

    public void updateUseCount(String tagName) {
        XyCursor cursor = null;
        try {
            cursor = BizportDBManager.query(TABLE_NAME, new String[]{KEY_USE_COUNT}, KEY_TAG_NAME + " =?", new String[]{tagName});
            if (cursor != null) {
                int count = 0;
                if (cursor.moveToFirst()) {
                    count = cursor.getInt(cursor.getColumnIndex(KEY_USE_COUNT));
                }
                count += 1;
                ContentValues values = new ContentValues();
                values.put(KEY_USE_COUNT, count);
                values.put(KEY_LAST_USE_TIME, System.currentTimeMillis());
                BizportDBManager.update(TABLE_NAME, values, KEY_TAG_NAME + "=?", new String[]{tagName});
            }
        } catch (Throwable t) {
            LogManager.e(TAG, "updateUseCount", t);
        } finally {
            XyCursor.closeCursor(cursor, true);
        }
    }


    public String getSceneIdsByTagName(String tagName1) {
        XyCursor cursor = null;
        String sceneIds = null;
        try {
            cursor = BizportDBManager.query(TABLE_NAME, new String[]{KEY_SCENE_IDS}, KEY_TAG_NAME + " =?", new String[]{tagName1});
            if (cursor == null) {
                return null;
            }
            if (cursor.moveToFirst()) {
                sceneIds = cursor.getString(cursor.getColumnIndex(KEY_SCENE_IDS));
            }
        } catch (Throwable t) {
            LogManager.e(TAG, "getSceneIdsByTagName", t);
        } finally {
            XyCursor.closeCursor(cursor, true);
        }
        return sceneIds;
    }

    public boolean isContain(String tagId) {
        XyCursor cursor = null;
        try{

            cursor = BizportDBManager.query(TABLE_NAME, null, KEY_TAG_ID + "=? ", new
                    String[]{tagId});
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    return true;
                }
            }
        }catch (Throwable t) {
            LogManager.e(TAG, "isContain", t);
        } finally {
            XyCursor.closeCursor(cursor, true);
        }
        return false;
    }

    public String getMaxVersion() {
        String version = SysParamEntityManager.getStringParam(Constant.getContext(), MAX_TAG_VERSION);
        if (version == null || version.isEmpty()) {
            version = "1";
        }
        return version;
    }

    public void updateData(List<TagSceneIdItem> data) {
        if (data == null || data.size() == 0)
            return;
        SQLiteDatabase db = null;
        try {
            db = BizportDBManager.getSQLiteDatabase();
            db.beginTransaction();
            for (TagSceneIdItem item : data) {

                if (item.getStatus() == -1) {
                    //delete
                    deleteTag(item.getTagId());
                } else {
                    //insert or update
                    int row = db.update(TABLE_NAME, tagItemToContentValues(item), KEY_TAG_ID + "=? ", new String[]{String.valueOf(item.getTagId())});
                    if (row <= 0)
                        db.insert(TABLE_NAME, null, tagItemToContentValues(item));
                }
            }
            String lastVersion = data.get(data.size() - 1).getVersion();
            SysParamEntityManager.setParam(MAX_TAG_VERSION, lastVersion);
        } catch (Throwable t) {
            LogManager.e(TAG, "updateData", t);
        } finally {
            if(db!=null && db.inTransaction()){
                db.setTransactionSuccessful();
                db.endTransaction();
            }
            BizportDBManager.close(db);
        }
    }

    private ContentValues tagItemToContentValues(TagSceneIdItem item) {
        ContentValues values = new ContentValues();
        values.put(KEY_TAG_ID, item.getTagId());
        values.put(KEY_TAG_NAME, item.getTagName());
        values.put(KEY_TAG_PARENT_IDS, item.getParentTagIds() == null ? "" : item.getParentTagIds());
        values.put(KEY_SCENE_IDS, item.getSceneIds());
        values.put(KEY_PRIORITY, item.getPriority());
        values.put(KEY_OFTEN_STATUS, item.getOftenStatus());
        values.put(KEY_VERSION, item.getVersion());
        return values;
    }

}